package com.healthcare.admin.utils;


import com.healthcare.common.constants.ResultCodeEnum;
import com.healthcare.common.exception.KetaiException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.ServletException;
import java.util.Date;

/**
 * 作者：LSH
 * 日期：2020/1/12 22:14
 */
public class JwtUtil {
    // 私钥uid
    final static String base64EncodedSecretKey = "2168a0c2-7205-4162-a3c6-d50305374888";//私钥uuid
    // 过期时间，默认设置5分钟
    final static  long TOKEN_EXP = 1000 * 60 * 5;

    public static  String getToken(String userName){
        return Jwts.builder()
                .setSubject(userName)
                .claim("roles","admin")
                .setIssuedAt(new Date())  // token得生效时间
                .setExpiration(new Date((System.currentTimeMillis()+TOKEN_EXP))) //过期时间
                .signWith(SignatureAlgorithm.HS256,base64EncodedSecretKey) // 签名加密
                .compact();
    }

    /**
     * 检查token
     * @param token
     * @return
     * @throws ServletException
     */
    public static Claims checkToken(String token)throws ServletException {
        try {
            final  Claims claims = Jwts.parser().setSigningKey(base64EncodedSecretKey).parseClaimsJws(token).getBody();
            return  claims;
        }catch (ExpiredJwtException el){ // 抛出自定义异常信息
            throw  new KetaiException(ResultCodeEnum.USERLOGIN_INVALID_ERROR);
        }catch (Exception e){
            throw new KetaiException(ResultCodeEnum.USERLOGIN_ERROR);
        }
    }
}
